<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.sql.*" import="Connect.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<title>Hammer Time Auctions</title>
</head>
<body>
	<div id="content">
		<%@include file="header.jsp"%>
		<h1>Success</h1>
		<hr></hr>
		<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
		<%@ page import="javax.servlet.http.*"%>
		<%@ page import="org.apache.commons.fileupload.*"%>
		<%@ page import="org.apache.commons.fileupload.disk.*"%>
		<%@ page import="org.apache.commons.fileupload.servlet.*"%>
		<%@ page import="org.apache.commons.io.output.*"%>
		<%
			//////////////////////////////////////////// Extract input submitted by form input ///////////////////////////////////////////////////////////////
			// Text input variables.
			String name = "";
			String year = "";
			String type = "";
			String description = "";

			// Store the location to write the file and the submitted file.
			File file = null;
			FileItem input = null;

			int maxFileSize = 5000 * 1024;
			int maxMemSize = 5000 * 1024;
			ServletContext context = pageContext.getServletContext();
			//String filePath = context.getInitParameter("file-upload");//-------------------------------------------------
			String filePath = application.getRealPath("item_images") + "\\";

			// Verify the content type
			String contentType = request.getContentType();
			if ((contentType.indexOf("multipart/form-data") >= 0)) {

				DiskFileItemFactory factory = new DiskFileItemFactory();
				// maximum size that will be stored in memory
				factory.setSizeThreshold(maxMemSize);
				// Location to save data that is larger than maxMemSize.
				//factory.setRepository(new File("c:\\temp"));//----------------------------------------------------------
				factory.setRepository(new File(filePath));

				// Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload(factory);
				// maximum file size to be uploaded.
				upload.setSizeMax(maxFileSize);
				try {
					// Parse the request to get file items.
					@SuppressWarnings("unchecked")
					List<FileItem> fileItems = upload.parseRequest(request);

					// Process the uploaded file items
					Iterator<FileItem> i = fileItems.iterator();

					while (i.hasNext()) {
						FileItem fi = (FileItem) i.next();
						if (!fi.isFormField()) {
							// Get the uploaded file parameters
							String fieldName = fi.getFieldName();
							String fileName = fi.getName();
							boolean isInMemory = fi.isInMemory();
							long sizeInBytes = fi.getSize();
							// Write the file
							if (fileName.lastIndexOf("\\") >= 0) {
								file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
							} else {
								file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
							}
							//fi.write(file);
							input = fi; // Store the submitted file. Do not write until the text components have been validated.
						} else {
							// FileItem is a form field.
							String value = fi.getString();
							if (fi.getFieldName().equalsIgnoreCase("name")) {
								name = value;
							} else if (fi.getFieldName().equalsIgnoreCase("year")) {
								year = value;
							} else if (fi.getFieldName().equalsIgnoreCase("type")) {
								type = value;
							} else if (fi.getFieldName().equalsIgnoreCase("description")) {
								description = value;
							}
						}
					}
					out.println("</body>");
					out.println("</html>");
				} catch (Exception ex) {
					out.println(ex);
					ex.printStackTrace();
				}
			}

			/////////////////////////////////////////////////////// Validate input ///////////////////////////////////////////////////////////////////////////
			// No name tests yet.
			boolean name_test = true;
			// Test if year is a non negative four digit number.
			boolean year_test = year.length() == 4;
			try {
				int num = Integer.parseInt(year);
				if (num < 0) {
					year_test = false;
				}
			} catch (Exception e) {
				year_test = false;
			}
			// No type tests yet.
			boolean type_test = true;
			// No description tests yet.
			boolean description_test = true;
			// Test if uploaded file is an image.
			boolean picture_test = true;
			String file_type = file.getName().substring(file.getName().lastIndexOf(".") + 1);
			if (!file_type.equalsIgnoreCase("gif") && !file_type.equalsIgnoreCase("jpg") && !file_type.equalsIgnoreCase("jpeg")
					&& !file_type.equalsIgnoreCase("png")) {
				picture_test = false;
			}
			// 	if (file.getName().equalsIgnoreCase("item_images")) {
			// 		picture_test = true;
			// 	}

			// Compile the error messages together.
			String errors = "";
			if (!name_test) {
				errors += "<br />";
			}
			if (!year_test) {
				errors += "* Year must be a non-negative 4 digit integer.<br />";
			}
			if (!type_test) {
				errors += "<br />";
			}
			if (!description_test) {
				errors += "<br />";
			}
			if (!picture_test) {
				errors += "* The picture must be a GIF, JPG, or PNG file.<br />";
			}

			// If there are any errors abort registration and send the user back to the
			// register page. It also saves non-password type data that the user has submitted.
			if (!errors.equals("")) {
				session.setAttribute("register_errors", errors);
				session.setAttribute("name", name);
				session.setAttribute("year", year);
				session.setAttribute("type", type);
				session.setAttribute("description", description);
				response.sendRedirect("add_item.jsp");
			} else {

				// Getting information and updating the database.
				java.sql.Connection conn = null;
				try {
					// Connect to the database.
					Class.forName(ConnectionInfo.myJDBCDriver()).newInstance();
					java.util.Properties sysprops = System.getProperties();
					sysprops.put("user", ConnectionInfo.myUserID());
					sysprops.put("password", ConnectionInfo.myPassword());
					conn = java.sql.DriverManager.getConnection(ConnectionInfo.myURL(), sysprops);

					// Check if the requested item exists.
					java.sql.Statement statement = conn.createStatement();
					java.sql.ResultSet rs = statement.executeQuery("SELECT name FROM items WHERE name = '" + name + "'" + "AND year='" + year + "'"
							+ "AND type='" + type + "'");
					if (rs.next()) {
						// Item already exists.
						session.setAttribute("register_errors", "* An item with the same name, year, and type already exists.");
						session.setAttribute("name", name);
						session.setAttribute("year", year);
						session.setAttribute("type", type);
						session.setAttribute("description", description);
						response.sendRedirect("add_item.jsp");
					} else {
						// The item does not exist in the database yet.
						name = "'" + name + "'";
						year = "'" + year + "'";
						type = "'" + type + "'";
						String id = "'0'";
						String copies_available = "'0'";
						String copies_sold = "'0'";
						description = "'" + description + "'";
						statement.executeUpdate("INSERT INTO items (id, name, year, description, type, copies_available, copies_sold) VALUES (" + id
								+ "," + name + "," + year + "," + description + "," + type + "," + copies_available + "," + copies_sold + ")");

						// Copy the image onto the server.
						rs = statement.executeQuery("SELECT LAST_INSERT_ID()");
						rs.next();
						//file = new File(file.getParent() + "\\" + rs.getString(1) + "." + file_type);
						file = new File(file.getParent() + "\\" + rs.getString(1) + ".png"); // all file types are considered PNG
						input.write(file);

						// Redirect the user after adding the item. Clear the form_type variable.
						out.println("New item added! You will be redirected in 5 seconds.<br />");
						out.println("<a href=\"view_items.jsp\">Click here if you can't wait!</a>");
						response.setHeader("Refresh", "5; view_items.jsp");
					}
				} catch (Exception e) {
					e.printStackTrace();
					out.print(e.toString());
				} finally {
					try {
						conn.close();
					} catch (Exception ee) {
					}
				}
			}
		%>
	</div>
	<hr></hr>
	<%@include file="footer.jsp"%>
</body>
</html>